﻿package com.teaphy.coroutinecrawler.top_suspend

import kotlinx.coroutines.*

fun main() = runBlocking {

    println("start -->")

    launch {
        val deferred1 = async { generate1() }
        val deferred2 = async { generate2() }
        val deferred3 = async { generate3() }
//        val deferred4 = async { generate4() }

        try {
            val list = awaitAll(deferred1, deferred2, deferred3)
//                val list = awaitAll(deferred1, deferred2, deferred3, deferred4)
            println("生成的值列表：$list")
        } catch (e: Exception) {
            println("生成值的异常为：$e")
        }

    }

    println("--> end")
}

suspend fun generate1(): Int {
    return withContext(Dispatchers.IO) {
        delay(1000)
        1
    }
}

suspend fun generate2(): Int {
    return withContext(Dispatchers.IO) {
        delay(2000)
        2
    }
}

suspend fun generate3(): Int {
    return withContext(Dispatchers.IO) {
        delay(3000)
        3
    }
}

//@Throws(Exception::class)
//suspend fun generate4(): Int {
//    return withContext(Dispatchers.IO) {
//        delay(2000)
//        throw  Exception("生成4失败")
//    }
//}